package com.gs.wzweather.service.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gs.wzweather.dao.ForeDayDao;
import com.gs.wzweather.entity.DSBean;
import com.gs.wzweather.bo.ForeDayTypeToken;
import com.gs.wzweather.bo.ForeHourTypeToken;
import com.gs.wzweather.config.datasource.DatasourceKey;
import com.gs.wzweather.config.datasource.TargetDataSource;
import com.gs.wzweather.dao.ChannelDao;
import com.gs.wzweather.dao.PortDao;
import com.gs.wzweather.entity.*;
import com.gs.wzweather.service.ForeService;
import com.gs.wzweather.utils.Constant;
import com.gs.wzweather.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.FutureTask;

/*

 */
@Service
@TargetDataSource(DatasourceKey.DB2)
public class ForeServiceImpl implements ForeService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    Gson gson = new Gson();

    @Autowired
    PortDao portDao;

    @Autowired
    ChannelDao channelDao;

    @Autowired
    ForeDayDao foreDayDao;

    @Override
    public List<Port> queryPortFore() {
        List<Port> ports = null;
        try {
            ports = portDao.queryAllPort();
            if (ports == null) {
                return null;
            } else {
                for (int i = 0; i < ports.size(); i++) {
                    Port port = ports.get(i);
                    if (port.isLocked()) {
                        ports.remove(i);
                        i--;
                    } else {
                        logger.info("port_staId->{}", port.getStationId());
                        //24小时预报
                        FutureTask<List<ForeHourTypeToken.DSBean>> fore24 = new FutureTask(() -> {
                            List<ForeHourTypeToken.DSBean> fore24h = getFore24h(port.getStationId());
                            return fore24h;
                        });
                        //7天预报
                        FutureTask<List<DSBean>> fore7 = new FutureTask(() -> {
                            List<DSBean> fore7d = get3OR7ForeDay(port.getStationId(), true);
                            return fore7d;
                        });

                        List<DSBean> fore7Result;
                        new Thread(fore24).start();
                        new Thread(fore7).start();

                        fore7Result = foreDayDao.queryPortFore(port.getStationId());
                        if (fore7Result == null||fore7Result.size()==0) {
                            fore7Result = fore7.get();
                        }

                        List<ForeHourTypeToken.DSBean> fore24Result = fore24.get();
                        port.getFore24hList().addAll(fore24Result);
                        port.getFore7dList().addAll(fore7Result);
                    }
                }
                return ports;
            }
        } catch (Exception e) {
            logger.info("queryPortFore->{}", e.getMessage());
            return ports;
        }

    }

    @Override
    public List<Channel> queryChannelFore() {
        List<Channel> channels ;
        try {
            channels = channelDao.queryAllChannel();
            if (channels == null) {
                return null;
            } else {
                for (int i = 0; i < channels.size(); i++) {
                    Channel channel = channels.get(i);
                    if (channel.isLocked()) {
                        channels.remove(i);
                        i--;
                    } else {
                        logger.info("channel_staId->{}", channel.getStationId());
                        //24小时预报
                        FutureTask<List<ForeHourTypeToken.DSBean>> fore24 = new FutureTask(() -> {
                            List<ForeHourTypeToken.DSBean> fore24h = getFore24h(channel.getStationId());
                            return fore24h;
                        });

                        //3天预报
                        FutureTask<List<DSBean>> fore3 = new FutureTask(() -> {
                            List<DSBean> fore3d = get3OR7ForeDay(channel.getStationId(), false);
                            return fore3d;
                        });

                        List<DSBean> fore3Result;
                        new Thread(fore24).start();
                        new Thread(fore3).start();

                        fore3Result = foreDayDao.queryChannelFore(channel.getStationId());
                        if (fore3Result == null||fore3Result.size()==0) {
                            fore3Result = fore3.get();
                        }

                        List<ForeHourTypeToken.DSBean> fore24Result = fore24.get();
                        channel.getFore24hList().addAll(fore24Result);
                        channel.getFore3dList().addAll(fore3Result);
                    }
                }
                return channels;
            }
        } catch (Exception e) {
            logger.info("queryChannelFore->{}", e.getMessage());
            return null;
        }
    }


    /*
        winds：风速
        windd：风向
        ww1：1小时天气现象
        t：温度
        pr01：1小时降水量
     */
    public List<ForeHourTypeToken.DSBean> getFore24h(String staId) {
        String element = "winds,windd,ww1,t,pr01";
        String url = Constant.Url.FORE_24_HOUR + Constant.Url.PARAM_STAID + staId + Constant.Url.PARAM_ELEMENT + element;
        try {
            String result = HttpUtils.request(url);
            ForeHourTypeToken foreHour = gson.fromJson(result, new TypeToken<ForeHourTypeToken>() {
            }.getType());
            if (foreHour.getReturnCode() == 0) {
                List<ForeHourTypeToken.DSBean> ds = foreHour.getDS();
                for (int i = 0; i < ds.size(); i++) {
                    ForeHourTypeToken.DSBean bean = ds.get(i);
                    bean.setTime(foreHour.getTime());
                    bean.setWw1(bean.getWw1().equals("-999.0") ? "0.0" : bean.getWw1());
                    bean.setPr01(bean.getPr01().equals("-999.0") ? "0.0" : bean.getPr01());
                }
                return ds;
            }
        } catch (Exception e) {
            logger.info("getFore24h->{}", e.getMessage());
        }
        return null;
    }

    /*
        winds：风速
        windd：风向
        pr24：24小时降水量
        t：温度
        ww12:12小时天气
     */
    public List<DSBean> get3OR7ForeDay(String staId, boolean isPort) {
        List<DSBean> result = new ArrayList<>();
        String element = "winds,windd,t,pr24,ww12";
        //  int count = 0;
        try {
            String response = HttpUtils.request(Constant.Url.FORE_7_DAY + Constant.Url.PARAM_STAID + staId + Constant.Url.PARAM_ELEMENT + element);
            //logger.info("get3OR7ForeDay->{}", response);
            ForeDayTypeToken foreDay = gson.fromJson(response, new TypeToken<ForeDayTypeToken>() {
            }.getType());
            if (foreDay.getReturnCode() == 0) {
                List<DSBean> ds = foreDay.getDS();
                for (int i = 1; i < ds.size(); i++) {
                    if (i % 2 != 0) {
                        DSBean bean = ds.get(i);
                        bean.setTime(foreDay.getTime());
                        bean.setWw12(bean.getWw12().equals("-999.0") ? "0.0" : bean.getWw12());
                        bean.setPr24(bean.getPr24().equals("-999.0") ? "0.0" : bean.getPr24());
                        if (isPort) {
                            if (result.size() < 7) {
                                result.add(bean);
                            }
                        } else {
                            if (result.size() < 3) {
                                result.add(bean);
                            }
                        }
                    }
                }
                return result;
            }
        } catch (Exception e) {
            logger.info("get3OR7ForeDay->{}", e.getMessage());
        }
        return null;
    }
}
